package com.alliky.core.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alliky.core.R;
import com.alliky.core.bus.RxMessager;
import com.alliky.core.loader.Loader;
import com.alliky.core.util.RxToast;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * @Description TODO
 * @Author wxianing
 * @Date 2020-11-14
 */
public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends RxAppCompatActivity implements IBaseView {
    protected V binding;
    protected VM mViewModel;
    private int viewModelId;
    public Context mContext;
    private Loader mLoader = null;

    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);

        AppManager.getInstance().addActivity(this);
        //上下文
        //页面接受的参数方法

        //私有的初始化Databinding和ViewModel方法
        initViewDataBinding(savedInstanceState);
        //私有的ViewModel与View的契约事件回调逻辑
        registorUIChangeLiveDataCallBack();
        //页面数据初始化方法
        initData();
        //页面事件监听的方法，一般用于ViewModel层转到View层的事件注册
        initViewObservable();
        //注册RxBus
        mViewModel.registerRxBus();

        ImmersionBar.with(this).statusBarDarkFont(false)
                .statusBarColor(R.color.blue)
                .fitsSystemWindows(true).init();

        mContext = this;
        mLoader = new Loader(mContext);
        initParam();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除Messenger注册
        RxMessager.getDefault().unregister(mViewModel);
        if (mViewModel != null) {
            mViewModel.removeRxBus();
        }
        if (binding != null) {
            binding.unbind();
        }
        if (mLoader != null) {
            mLoader.destory();
            mLoader = null;
        }
    }

    /**
     * 注入绑定
     */
    private void initViewDataBinding(Bundle savedInstanceState) {
        //DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包
        binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState));
        viewModelId = initVariableId();
        mViewModel = initViewModel();
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) createViewModel(this, modelClass);
        }
        //关联ViewModel
        binding.setVariable(viewModelId, mViewModel);
        //支持LiveData绑定xml，数据改变，UI自动会更新
        binding.setLifecycleOwner(this);
        //让ViewModel拥有View的生命周期感应
        getLifecycle().addObserver(mViewModel);
        //注入RxLifecycle生命周期
        mViewModel.injectLifecycleProvider(this);
        mViewModel.setContext(this);
    }

//    public void createViewModel() {
//        if (mViewModel == null) {
//            Class modelClass;
//            Type type = getClass().getGenericSuperclass();
//            if (type instanceof ParameterizedType) {
//                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
//            } else {
//                //如果没有指定泛型参数，则默认使用BaseViewModel
//                modelClass = BaseViewModel.class;
//            }
//            mViewModel = (VM) ViewModelProviders.of(this).get(modelClass);
//            mViewModel.setObjectLifecycleTransformer(bindToLifecycle());
//        }
//    }

    //刷新布局
    public void refreshLayout() {
        if (mViewModel != null) {
            binding.setVariable(viewModelId, mViewModel);
        }
    }


    /**
     * =====================================================================
     **/
    //注册ViewModel与View的契约UI回调事件
    protected void registorUIChangeLiveDataCallBack() {
        mViewModel.getUC().getShowMessage().observe(this, (Observer<String>) message -> RxToast.normal(message));

        //加载对话框显示
        mViewModel.getUC().getShowDialogEvent().observe(this, (Observer<String>) title -> showLoading(title));
        //加载对话框消失
        mViewModel.getUC().getDismissDialogEvent().observe(this, (Observer<Void>) v -> hideLoading());
        //跳入新页面
        mViewModel.getUC().getStartActivityEvent().observe(this, (Observer<HashMap<String, Object>>) params -> {
            Class<?> clz = (Class<?>) params.get(BaseViewModel.ParameterField.CLASS);
            Bundle bundle = (Bundle) params.get(BaseViewModel.ParameterField.BUNDLE);
            startActivity(clz, bundle);
        });
        //跳入ContainerActivity
        mViewModel.getUC().getStartContainerActivityEvent().observe(this, (Observer<HashMap<String, Object>>) params -> {
            String canonicalName = (String) params.get(BaseViewModel.ParameterField.CANONICAL_NAME);
            Bundle bundle = (Bundle) params.get(BaseViewModel.ParameterField.BUNDLE);
            startContainerActivity(canonicalName, bundle);
        });

        mViewModel.getUC().getSetResultEvent().observe(this, (Observer<Intent>) intent -> {
            setResult(Activity.RESULT_OK, intent);
            finish();
        });

        //关闭界面
        mViewModel.getUC().getFinishEvent().observe(this, (Observer<Void>) v -> finish());
        //关闭上一层
        mViewModel.getUC().getOnBackPressedEvent().observe(this, (Observer<Void>) v -> onBackPressed());
    }

    public void showLoading(String message) {
        if (mLoader != null) {
            mLoader.showLoading(message);
        }
    }

    public void hideLoading() {
        if (mLoader != null) {
            mLoader.hideLoading();
        }
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(this, clz));
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     */
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Intent intent = new Intent(this, ContainerActivity.class);
        intent.putExtra(ContainerActivity.FRAGMENT, canonicalName);
        if (bundle != null) {
            intent.putExtra(ContainerActivity.BUNDLE, bundle);
        }
        startActivity(intent);
    }

    /**
     * =====================================================================
     **/
    @Override
    public void initParam() {

    }

    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    public abstract int initContentView(Bundle savedInstanceState);

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    public abstract int initVariableId();

    /**
     * 初始化ViewModel
     *
     * @return 继承BaseViewModel的ViewModel
     */
    public VM initViewModel() {
        return null;
    }

    @Override
    public void initData() {
    }

    @Override
    public void initViewObservable() {
    }

    /**
     * 创建ViewModel
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T extends ViewModel> T createViewModel(AppCompatActivity activity, Class<T> cls) {
        return new ViewModelProvider(activity).get(cls);
    }
}
